package ;

import flash.display.Loader;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.EventDispatcher;

/**
 * ...
 * @author m
 */

class Resources extends EventDispatcher
{
	public static var IMGS_LOADED: String = "imgsLoaded";	  
	public static var LOAD_ERROR: String = "loadError";
	
	public static var Inst: Resources;
	
	var loadersArray: Array<Loader>;
	var idsArray: Array<Int>;
	var namesArray: Array<String>;
	var numImgs: Int;
	var numLoaded: Int;
	var isError: Bool;
	var bitmaps: IntHash<BitmapData>;

	public function new() 
	{
		super();
		
		isError = false;
		numImgs = 0;
		numLoaded = 0;
		
		namesArray = new Array<String>();
		idsArray = new Array<Int>();
		bitmaps = new IntHash<BitmapData>();
		loadersArray = new Array<Loader>();
	}
	
	static public function Init()
	{
		Inst = new Resources();
	}
	
	public function AddSprite(id: Int, resourceName: String)
	{	
		namesArray.push(resourceName);
		idsArray.push(id);
		
		numImgs++;
	}
	
	public function GetSprite(id: Int) : Bitmap
	{
		var data: BitmapData = bitmaps.get(id);
		if (data != null)
			return new Bitmap(data);
		return null;
	}

	public function GetBitmapData(id: Int) : BitmapData
	{
		var data: BitmapData = bitmaps.get(id);
		if (data != null)
			return data;
		return null;
	}
	
	public function Load()
	{
		isError = false;
		numLoaded = 0;

		//trace("start loading images: " + numImgs);
				
		for (i in 0...numImgs) {			   
			loadersArray.push(new Loader());
			loadersArray[i].contentLoaderInfo.addEventListener(flash.events.Event.COMPLETE, imgLoaded);
			loadersArray[i].contentLoaderInfo.addEventListener(flash.events.IOErrorEvent.IO_ERROR, errorOccured);
			loadersArray[i].load(new flash.net.URLRequest(namesArray[i]));
		}			
	}
	
	private function imgLoaded(void)
	{
		numLoaded++;
		
		//trace("images loaded successfully: " + numLoaded);
		
		if (!isError && numLoaded == numImgs)
		{
		    for (i in 0...numImgs) {
				bitmaps.set(idsArray[i], untyped loadersArray[i].content.bitmapData);
				loadersArray[i].contentLoaderInfo.removeEventListener(flash.events.Event.COMPLETE, imgLoaded);
				loadersArray[i].contentLoaderInfo.removeEventListener(flash.events.IOErrorEvent.IO_ERROR, errorOccured);
				loadersArray[i] = null;
		    }
			
 		    loadersArray = [];
			
			dispatchEvent(new flash.events.Event(IMGS_LOADED));			
		}
	}
	
	private function errorOccured(void)
	{
		isError = true;

		dispatchEvent(new flash.events.Event(LOAD_ERROR));
		
		trace("images load error");
	}	
}